"""
简化版家庭管理系统模型
"""

from tortoise import fields
from app.models.base.base import BaseModel


class FamilyMember(BaseModel):
    """家庭成员模型"""
    user = fields.ForeignKeyField('models.User', related_name='family_memberships')
    family = fields.ForeignKeyField('models.Family', related_name='members')
    
    nickname = fields.CharField(max_length=50, null=True, description="家庭昵称")
    avatar = fields.CharField(max_length=255, null=True, description="成员头像")
    is_admin = fields.BooleanField(default=False, description="是否为管理员")
    is_active = fields.BooleanField(default=True, description="是否激活")
    joined_at = fields.DatetimeField(auto_now_add=True, description="加入时间")
    
    # 权限控制
    permissions = fields.JSONField(default=list, description="额外权限")
    
    class Meta:
        table = "family_members"
        table_description = "家庭成员表"
        unique_together = (("user", "family"),)
        
    def __str__(self):
        return f"FamilyMember(user_id={self.user_id}, family_id={self.family_id})"



class Family(BaseModel):
    """家庭模型（简化版）"""
    name = fields.CharField(max_length=50, description="家庭名称")
    description = fields.TextField(null=True, description="家庭描述")
    avatar = fields.CharField(max_length=255, null=True, description="家庭头像")
    is_active = fields.BooleanField(default=True, description="是否激活")
    order = fields.IntField(default=0, description="排序")
    parent_id = fields.IntField(default=0, description="父家庭ID")
    
    # 家庭属性
    max_members = fields.IntField(default=20, description="最大成员数")
    created_by = fields.ForeignKeyField('models.User', related_name='created_families')

    class Meta:
        table = "families"
        table_description = "家庭表"
        
    def __str__(self):
        return f"Family(id={self.id}, name={self.name})"
    
    async def get_children(self):
        """获取直接子家庭"""
        return await Family.filter(parent_id=self.id, is_active=True)
    
    async def get_members_count(self):
        """获取家庭成员数量"""
        return await FamilyMember.filter(family=self, is_active=True).count()
    
    async def is_full(self):
        """检查家庭是否已满员"""
        member_count = await self.get_members_count()
        return member_count >= self.max_members

